package com.atguigu.mqdemo.consumer.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class RabbitmqListener {
    /*
        RabbitListener标注的方法为一个消费者方法
        配置队列时：
            1、如果队列已存在  直接通过queues属性配置队列名称
            2、队列不存在 需要通过注解创建
     */
    @RabbitListener(queues = {
        "demo1.queue","demo2.queue"
    })
    public void demo1Listener(String msg , Channel channel , Message message) throws IOException {
        try {
            System.out.println("消费者获取到消息：" + msg);
            int  i = 1/0;
            channel.basicAck(message.getMessageProperties().getDeliveryTag() ,false);
        } catch (Exception e) {
            e.printStackTrace();
            //消费消息的业务出现异常，手动ack失败
            if(message.getMessageProperties().isRedelivered()){
                //如果再次消费仍然失败 丢弃消息
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),
                        false);
            }else{
                //第一次消费出现异常可以让消息重新归队 再次消费
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,
                            true);
            }

        }
    }

    @RabbitListener(queues = {
            "delay.queue"
    })
    public void delayListener(String msg , Channel channel ,Message message) throws IOException {
        try {
            System.out.println("延迟队列消费者："+ msg);
            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
        } catch (Exception e) {
//            e.printStackTrace();
            if(message.getMessageProperties().isRedelivered()){
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag() , false,true);
            }
        }
    }

    //注解创建交换机 队列 绑定
    @RabbitListener(bindings = {
            @QueueBinding(
                value = @Queue(name = "demo3.queue",ignoreDeclarationExceptions = "true"),
                exchange = @Exchange(name = "demo3.exchange" , ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC),
                key = "demo3.#"
            )
    })
    public void demo3Listener(Map<String,String> map , Channel channel , Message message) throws IOException {
        System.out.println(JSON.toJSONString(map));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
